package com.ghsc.ghxc.jsb.ui.message.activity

import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.event.SchedulerTransformer
import com.cn.appcore.ext.showToast
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.ActivityFriendsListBinding
import com.ghsc.ghxc.jsb.ui.message.bean.ChatDataResultBean
import com.ghsc.ghxc.jsb.ui.message.view.RouterUtils
import com.ghsc.ghxc.jsb.view.NotDataView
import com.scwang.smart.refresh.layout.api.RefreshLayout

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.message.activity
 * 类名：MyGroupListActivity
 * 创建时间：2024/5/9 16:08
 * 创建人 @author： xiaolin
 * 描述 ：Todo...我的群聊list
 */
class MyGroupListActivity : BaseVMActivity<MessageViewModel, ActivityFriendsListBinding>() {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_friends_list
    }

    override fun attachVMClass(): Class<MessageViewModel>? {
        return MessageViewModel::class.java
    }
    private val mAdapter: SearchChatAdapter by lazy { SearchChatAdapter() }
    var mList = arrayListOf<ChatDataResultBean>()
    private var notDataView: View? = null
    var itemPosition =-1

    var keyword:String=""

    override fun initBar() {
        super.initBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }
    override fun initView() {
        binding.run {
            llSearch.visibility= View.GONE
            bar.topTitle.text="我的社群"
            bar.topLeftView.setOnClickListener { finish() }
            etSearch.hint = "请输入群号/群标题"
        }

        binding.rvList.layoutManager = LinearLayoutManager(this)
        binding.rvList.adapter = mAdapter
        mAdapter.setNewInstance(mList)
        notDataView = NotDataView.notDataView(this, binding.rvList, binding.refreshLayout,"暂无数据")
        mAdapter.setOnItemClickListener { adapter, view, position ->
            //跳转到群聊
            RouterUtils.startToJumpGoup(this,mAdapter.getItem(position).tid)

        }
        mAdapter.addChildClickViewIds(R.id.tvBtnShenHe)
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            //跳转申请群的列表
            when(view.id){
                R.id.tvBtnShenHe ->{
                    var  bundle = Bundle()
                    bundle.putString("gid",mAdapter.getItem(position).gid)
                    bundle.putInt("groupPosition",position)
                    startActivity(GroupApplyListActivity().javaClass,bundle)
                }
            }
        }
        initRefreshLayout()
        pageNo = 1
        getListData()

        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean::class.java)
            .compose(SchedulerTransformer())
            .subscribe { rxBusBean ->
                when {
                    rxBusBean.id == CustKey.DATA_COUNT_ITEM && rxBusBean.sign == CustKey.DATA_COUNT_ITEM -> {
//                        val itemP =rxBusBean.index
//                        val itemCount =rxBusBean.anyBean as Int
//                        mAdapter.getItem(itemP).applycnt=itemCount
//                        mAdapter.notifyItemChanged(itemP)
                        pageNo = 1
                        getListData()
                    }
                }
            }

    }

    override fun initClickListener() {
        super.initClickListener()
        binding.run {
            tvBtnNext.setOnClickListener {
                if (TextUtils.isEmpty(binding.etSearch.text)){
                    showToast("请输入群号/群标题")
                }else{
                    keyword=binding.etSearch.text.toString()
                    pageNo = 1
                    getListData()
                }
            }
            etSearch.isFocusable = true
            etSearch.isFocusableInTouchMode = true
            etSearch.requestFocus()
            etSearch.setOnEditorActionListener(object : TextView.OnEditorActionListener {
                override fun onEditorAction(
                    v: TextView,
                    actionId: Int,
                    event: KeyEvent?
                ): Boolean {
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        // 先隐藏键盘
                        hideKeyboard(v)
                        keyword = binding.etSearch.text.toString().trim()
                        if (!TextUtils.isEmpty(keyword)) {
                            binding.etSearch.clearFocus()
                            hideKeyboard(binding.etSearch)
                            pageNo = 1
                            getListData()
                        }else{
                            keyword=""
                            pageNo = 1
                            getListData()
                        }
                        return true
                    }
                    return false
                }
            })
            etSearch.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }
                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun afterTextChanged(p0: Editable?) {
                    if(TextUtils.isEmpty(p0.toString().trim())){
                        keyword=""
                        pageNo = 1
                        getListData()
                    }
                }

            })

        }
    }

    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                pageNo = 1
                getListData()
            }
            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
                pageNo++
                getListData()
            }
        })
    }
    private fun getListData() {
        val map: HashMap<String, Any> = HashMap()
        map["pindex"] = pageNo
        map["psize"] = pageSize
        map["keyword"] = keyword

        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onMyGroupListMethod(it1) }
    }

    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@MyGroupListActivity) {
                binding.refreshLayout.finishRefresh()
                showToast( it)
            }
            againLoginMsg.observe(this@MyGroupListActivity) {
                binding.refreshLayout.finishRefresh()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onActFriendData.observe(this@MyGroupListActivity){
//                同意加好友
                showToast("操作成功")
                if (itemPosition>-1){
                    mAdapter.getItem(itemPosition).status=1
                }
                mAdapter.notifyItemChanged(itemPosition)
            }
            onMyGroupListData.observe(this@MyGroupListActivity, Observer {
                //我的群聊 列表
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                if (pageNo == 1) {
                    if (it.data.list.isNullOrEmpty()){
                        mAdapter.replaceData( it.data.list)
                        mAdapter.setEmptyView(notDataView!!)
                    } else {
                        mAdapter.replaceData( it.data.list)
                    }
                } else {
                    if (!it.data.list.isNullOrEmpty())
                        mAdapter.addData(it.data.list)
                }
            })
        }
    }


    inner class SearchChatAdapter   : BaseQuickAdapter<ChatDataResultBean, BaseViewHolder>(
        R.layout.group_list_item) {
        override fun convert(helper: BaseViewHolder, item: ChatDataResultBean) {
            GlideUtil.ImageHeadLoad(this.context,item.headimg,helper.getView(R.id.userImgUrl))
            helper.setText(R.id.tvName,item.name)
                .setGone(R.id.imgCheck,true)
            if(!TextUtils.isEmpty(item.shenhecnt)){
                helper.setGone(R.id.tvBtnShenHe,false)
                    .setText(R.id.tvBtnShenHe,item.shenhecnt)
            }else{
                helper.setGone(R.id.tvBtnShenHe,true)
            }

//            if (item.applycnt>0){
//                helper.setGone(R.id.tvBtnShenHe,false)
//                    .setText(R.id.tvBtnShenHe,item.applycnt.toString()+"个入群申请")
//            }else{
//                helper.setGone(R.id.tvBtnShenHe,true)
//            }


        }
    }
}